package _interview100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 15. 三数之和
 */
public class No15 {
    private final List<List<Integer>> answer = new ArrayList<>();

    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        for (int i = 0; i < nums.length - 2; i++) {
            if ((i > 0 && nums[i] == nums[i - 1]) || (nums[i] + nums[nums.length - 1] + nums[nums.length - 2] < 0))
                continue;
            if (nums[i] + nums[i + 1] + nums[i + 2] > 0) {
                break;
            }
            int target = -nums[i];
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                if (nums[left] + nums[right] == target) {
                    answer.add(List.of(nums[i], nums[left], nums[right]));
                    do {
                        left++;
                    } while (left < nums.length - 1 && nums[left] == nums[left - 1]);
                    do {
                        right--;
                    } while (right > 0 && nums[right] == nums[right + 1]);
                } else if (nums[left] + nums[right] < target) left++;
                else right--;
            }
        }
        return answer;
    }
}
